/*
 	Utility.cpp

 	Copyright (c) 2008 Bojan Rajkovic

 	Permission is hereby granted, free of charge, to any person obtaining a copy
 	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
 	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 	copies of the Software, and to permit persons to whom the Software is
 	furnished to do so, subject to the following conditions:

 	The above copyright notice and this permission notice shall be included in
 	all copies or substantial portions of the Software.

 	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 	THE SOFTWARE.
*/

#include "../include/Utility.h"
using namespace LinPulseApplet;

std::string Utility::FormatString(const char* fmt, ...) {
	if (fmt != NULL) {
 			
		va_list marker = NULL; 
		va_start(marker, fmt);
           			             	
		char* buffer;
 		vasprintf(&buffer, fmt, marker);    
		std::string retStr(buffer);
           
		// Reset variable arguments
		va_end(marker); 
				
		return retStr; 
	} else {
		return "";
	}
}

// Push a message to the log, specifying the message type as well
void Utility::LogMessage(std::string Message, int MessageType) {
	
	// we need a priority for syslog, it's a bitwise or of the
	// log message type LOG_SOMETHING and the log domain (also LOG_SOMETHING)
	int priority;
	
	// we'll assign the priority based on the message type
	// and the fact that we want to log to daemon.
	switch (MessageType) {
		case M_ERROR: priority = LOG_ERR | LOG_DAEMON; break;
		case M_INFO: priority = LOG_NOTICE | LOG_DAEMON; break;
		default: priority = LOG_INFO | LOG_DAEMON; break;
	}
	
	// open the log, specifying that we want to log the pid
	// along with the message to the daemon log (as determined by syslog)
	openlog("linpulse-applet", LOG_PID, LOG_DAEMON);
	// log the message. we use the "%s", message format because that's
	// the form recommended by man 3 syslog
	syslog(priority, "%s", Message.c_str());
	// close the log--not strictly required, but recommended
	closelog();
}
